<template>
  <div class="phone-form">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      size="large"
      @keyup.enter="login(ruleFormRef)"
    >
      <el-form-item prop="mobile">
        <el-input
          v-model="ruleForm.mobile"
          prefix-icon="iphone"
          clearable
          placeholder="请输入手机号"
        >
          <template #prepend>+86</template>
        </el-input>
      </el-form-item>
      <el-form-item prop="captcha">
        <div class="login-msg-vcode">
          <el-input
            v-model="ruleForm.captcha"
            prefix-icon="unlock"
            clearable
            placeholder="请输入验证码"
          />
          <el-button class="btn" :disabled="vcodeDisabled" @click="getVCode">
            获取验证码
            <span v-if="vcodeDisabled">{{ time }}</span>
          </el-button>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          round
          style="width: 100%"
          :loading="isLogin"
          @click="login(ruleFormRef)"
        >
          登录
        </el-button>
      </el-form-item>
      <el-form-item>
        <router-link to="">忘记密码？</router-link>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { loginCaptcha, loginByMobile } from '@api/login'
import { Encrypt } from '@utils/aes'
import { PhoneRuleForm } from '@interface/login'

const ruleFormRef = ref<FormInstance>()

const ruleForm = reactive<PhoneRuleForm>({
  mobile: '',
  captcha: ''
})

// 自定义校验规则
const validatorTel = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请填写手机号'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('手机号格式错误'))
  }
  callback()
}

const rules = reactive<FormRules<PhoneRuleForm>>({
  mobile: [{ validator: validatorTel, trigger: 'blur' }],
  captcha: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
})

// 倒计时
const time = ref<number>(60)
const vcodeDisabled = ref<boolean>(false)

// 加载状态
const isLogin = ref<boolean>(false)

// 获取验证码
const getVCode = async () => {
  const validate = await ruleFormRef.value?.validateField('mobile', () => undefined)
  if (!validate) {
    ElMessage.error('请填写正确的手机号')
  }

  const res = await loginCaptcha({
    mobile: Encrypt(ruleForm.mobile)
  })

  if (res.code !== '200') {
    ElMessage.error(res.msg)
    return
  }
  ElMessage.success('验证码发送成功')
  vcodeDisabled.value = true
  time.value = 60

  // 计时器
  const timer = setInterval(() => {
    time.value -= 1
    if (time.value < 1) {
      clearInterval(timer)
      vcodeDisabled.value = false
      time.value = 0
    }
  }, 1000)
}

// 登录
const login = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      const res = await loginByMobile({
        mobile: Encrypt(ruleForm.mobile),
        captcha: Encrypt(ruleForm.captcha)
      })
      if (res.code !== '200') {
        ElMessage.error(res.msg)
      }
    } else {
      ElMessage.warning('请填写正确内容')
    }
  })
}
</script>

<style lang="less" scoped>
.phone-form {
  .login-msg-vcode {
    display: flex;
    width: 100%;

    .btn {
      margin-left: 8px;
    }
  }
}
</style>
